<template>
    <Card class="no-border-card">
        <!--标题-->
        <p slot="title">
            电费代缴
        </p>
        <!--标题end-->

        <div class="margin-bottom-20">
            <i-input placeholder="房源地址/户号" v-model="search.keyword" style="width: 300px"></i-input>

            <Select v-model="search.sub_biz_type" style="width: 200px">
                <Option v-for="type in bizTypes" :key="type.id" :value="type.id">{{type.label}}</Option>
            </Select>

            <i-button @click="initData">搜索</i-button>
        </div>

        <Table :loading="loading" :columns="columns" :data="tableData"></Table>

        <Page
            :current.sync="pagination.page"
            :total="pagination.total"
            :page-size="pagination.page_size"
            show-total
            style="text-align:center"
            @on-change="initData"></Page>
    </Card>
</template>

<script>
import util from '@/libs/util'
import { mapState } from 'vuex'
import { http, api } from '@/libs/http'

export default {
  name: 'auto-deduct',
  computed: {
    // options() {
    //     if (!this.search.type) return [];
    //     return this.search.type === 1 ? this.payFirstOptions : this.payAfterOptions;
    // },
    ...mapState({
      roleId: state => state.user.roleId
    })
  },
  data () {
    return {
      bizTypes: [{
        label: '电费',
        id: 'ELECTRIC'
      }, {
        label: '水费',
        id: 'WATER'
      }, {
        label: '煤气费',
        id: 'GAS'
      }],
      loading: false,
      tableData: [],
      search: {
        type: '',
        status: '',
        keyword: '',
        sub_biz_type: 'ELECTRIC'
      },
      pagination: {
        page: 1,
        total: 1,
        page_size: 10
      },
      payFirstOptions: [{ id: 1, label: '余额不足(大于0小于10)' }, { id: 2, label: '欠费(小于0)' }],
      payAfterOptions: [{ id: 3, label: '欠费' }, { id: 4, label: '已经缴纳' }],
      modeMap: {
        2: '账单模式',
        4: '缴清欠费模式',
        5: '欠费自由缴模式'
      },
      columns: [
        {
          title: '房源/户号',
          render: (h, p) => (
            <span>
              {p.row.detail_address} / <b>{(p.row.home_no && p.row.home_no.home_no) || '无'}</b>
            </span>
          )
        },
        {
          title: '缴费模式',
          width: 160,
          render: (h, p) => {
            if (p.row.bills && p.row.bills.chargeMode) {
              return <span>{this.modeMap[+p.row.bills.chargeMode]}</span>
            }
          }
        },
        {
          title: '账户',
          render: (h, p) => {
            if (p.row.bills && p.row.bills.chargeMode) {
              const chargeMode = +p.row.bills.chargeMode
              return (
                <div>
                  {p.row.bills.instBills.map(bill => (
                    <div>
                                            缴纳金额: {bill.amount}元， 账单所有人：{bill.ownerName}
                      {chargeMode === 5 && <span>，当前余额: {bill.balance}元</span>}
                    </div>
                  ))}
                </div>
              )
            } else if (p.row.bills && p.row.bills.err_code) {
              return <span>{p.row.bills.err_msg}</span>
            }
          }
        },
        {
          title: '操作',
          width: 160,
          render: (h, p) => {
            return this.roleId === 100 && p.row.bills && p.row.bills.chargeMode ? (
              <i-button onClick={() => this.handlePay(p.row)}>缴费</i-button>
            ) : null
          }
        }
      ]
    }
  },
  created () {
    this.initData()
  },
  methods: {
    async initData () {
      try {
        this.loading = true
        const { keyword, sub_biz_type } = this.search
        const { page, page_size } = this.pagination
        this.tableData = await http.req(api.agency_pay_bills, null, { page, page_size, keyword: keyword || null, sub_biz_type })
      } catch (err) {
        console.log(err)
      } finally {
        this.loading = false
      }
    },
    handlePay (item) {
      if (!item.bills || Object.keys(item.bills).length === 0) {
        this.$Message.error('该记录没有账单')
      } else {
        const freeToPay = Number(item.bills.chargeMode) === 5
        freeToPay
          ? this.askPrice(item)
          : this.askConfirmPay(item)
      }
    },
    askConfirmPay (item) {
      this.$Modal.confirm({
        title: '提示',
        loading: true,
        content: util.escapeHtml(`房源:${item.detail_address}, 确定缴费?`),
        onOk: () => {
          const { bills } = item
          const instBills = bills.instBills.map(item => {
            let data = {
              unique_id: item.uniqId,
              amount: item.amount,
              bill_fines: item.billFines,
              balance: item.balance
            }
            if (item.instBillNo) data = { ...data, inst_bill_no: item.instBillNo }
            if (item.billDate) data = { ...data, bill_date: item.billDate }
            return data
          }).filter(item => parseFloat(item.amount) > 0)
          this.pay(item, instBills)
        }
      })
    },
    /** 自由缴费只有一个item */
    askPrice (item) {
      const bill = item.bills.instBills[0]
      // if (parseFloat(bill.amount) === 0) {
      //     this.$Message.info('该账单不需要交费');
      //     return;
      // }
      const amount = parseFloat(bill.amount)
      let val = amount
      this.$Modal.confirm({
        loading: true,
        render: (h) => <div>
          <h3 class="margin-bottom-20">填写缴费金额:</h3>
          <div class="margin-bottom-20">
            <span>缴费金额（ 大于等于{bill.amount} ）：</span>
            <input-number
              style="width: 140px"
              size="default"
              step={0.01}
              value={val}
              min={amount}
              onInput={n => { val = n }}></input-number>
          </div>
        </div>,
        onOk: () => {
          const instBills = [{
            amount: val + '',
            unique_id: bill.uniqId,
            bill_fines: bill.billFines,
            balance: bill.balance
          }]
          this.pay(item, instBills)
        }
      })
    },
    async pay (item, instBills) {
      try {
        const { id, bills, home_no } = item
        const data = {
          cache_key: bills.cacheKey,
          home_id: id,
          charge_mode: bills.chargeMode,
          biz_type: bills.bizType,
          sub_biz_type: bills.subBizType,
          bill_key: home_no.home_no,
          owner_name: bills.ownerName,
          charge_inst: bills.chargeInst,
          inst_bills: instBills
        }
        const res = await http.req(api.agency_pay_pay, null, { bills: [data] })
        if (res.some(item => !!item.bill_id)) {
          this.$Notice.success({
            duration: 10,
            title: '缴费成功',
            desc: '缴费信息将会同步到系统中，请勿重复缴费'
          })
        } else {
          const reason = res.map(item => item.msg).join(', ')
          this.$Message.error(reason)
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.$Modal.remove()
      }
    }
  }
}
</script>